package com.dc.docs._888_面试.concurrent._8_deadlock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

/**
 * Description: 死锁案例
 * @author: gdc
 * @date: 2021/6/17
 * @version 1.0
 */
@Data
@AllArgsConstructor
public class DeadLockDemo implements Runnable {
    /**
     * 资源 1
     */
    private String first;
    /**
     * 资源 2
     */
    private String second;

    @SneakyThrows
    @Override
    public void run() {
        synchronized (first) {
            System.out.println(Thread.currentThread().getName() + ", 获得：" + first);
            TimeUnit.SECONDS.sleep(1);

            synchronized (second) {
                System.out.println(Thread.currentThread().getName() + ", 获得: " + second);
            }
        }
    }

    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new DeadLockDemo(lockA, lockB), "线程1").start();
        new Thread(new DeadLockDemo(lockB, lockA), "线程2").start();
    }
}
